<template>
  <el-dialog :title="title" :visible.sync="visible" class="dialog-sm" append-to-body @close="close">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" v-loading="loading">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入角色名称" maxlength="64"/>
      </el-form-item>
      <el-form-item label="权限字符" prop="role_key">
        <el-input v-model="form.role_key" placeholder="请输入权限字符" maxlength="128"/>
      </el-form-item>
      <el-form-item label="角色顺序" prop="list_sort">
        <el-input-number v-model="form.list_sort" controls-position="right" :min="0" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio label="1">正常</el-radio>
          <el-radio label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单权限">
        <el-checkbox v-model="menuExpand" @change="handleTreeExpand">展开/折叠</el-checkbox>
        <el-checkbox v-model="menuNodeAll" @change="handleTreeNodeAll">全选/全不选</el-checkbox>
        <el-checkbox v-model="menuCheckStrictly">父子联动</el-checkbox>
        <el-tree
          class="tree-border"
          :data="menuOptions"
          show-checkbox
          ref="treeRef"
          node-key="id"
          :check-strictly="!menuCheckStrictly"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="250" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit" :loading="submitting" :disabled="loading">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addRoleApi, editRoleApi, infoRoleApi } from '@/api/system/role'
import { selectMenuApi } from '@/api/system/menu'

export default {
  name: 'RoleForm',
  props: {
    value: Boolean,
    id: Number|String,
  },
  data() {
    return {
      rowData: null,
      title: '',
      loading: false,
      submitting: false,
      form: { name: '', role_key: '', list_sort: 10, status: '1', remark: '', check_strictly: '0', menu_ids:[] },
      rules: {
        name: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
        role_key: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
        list_sort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }]
      },
      menuExpand: false,
      menuNodeAll: false,
      menuCheckStrictly: false,
      menuOptions: [],
      defaultProps: { children: "children", label: "name" },
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      this.form.id = this.id || undefined
      if (this.form.id) {
        this.title = '编辑角色'
        await this.getRowData()
      } else {
        this.title = '添加角色'
      }
      await this.getMenuOptions()
      this.loading = false
    },
    async handleSubmit() {
      this.$refs.formRef.validate(async valid=>{
        if(!valid || this.submitting) return
        this.submitting = true
        this.form.menu_ids = this.getAllCheckedKeys()
        this.form.check_strictly = this.menuCheckStrictly ? '1' : '0'
        try {
          await this.$modal.confirm('确定提交表单数据？')
          if (this.form.id) {
            await editRoleApi(this.form)
          } else {
            await addRoleApi(this.form)
          }
          this.close(true, '操作成功')
        } catch (e) {
          this.submitting = false
        }
      })
    },
    async getRowData() {
      try {
        const { info } = await infoRoleApi(this.form.id)
        this.dataToForm(this.form, info)
        this.menuCheckStrictly = this.form.check_strictly === 1
        this.rowData = info
      } catch (error) {
        this.close()
      }
    },
    async getMenuOptions(){
      try {
        const { list } = await selectMenuApi()
        this.menuOptions = this.listToTree(list)
        this.$nextTick(()=>{
          this.form.menu_ids.map(id=>{
            this.$refs.treeRef.setChecked(id,true,false)
          })
        })
      } catch (error) {}
    },
    close(submit = false, msg) {
      if (submit === true) this.$emit('submit')
      this.$emit('close', submit === true)
      if (msg) submit === true ? this.$modal.msgSuccess(msg) : this.$modal.msgError(msg)
      this.visible = false
    },
    handleTreeExpand(checked) {
      let treeList = this.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.treeRef.store.nodesMap[treeList[i].id].expanded = checked
      }
    },
    handleTreeNodeAll(checked) {
      this.$refs.treeRef.setCheckedNodes(checked ? this.menuOptions: [])
    },
    getAllCheckedKeys() {
      let checkedKeys = this.$refs.treeRef.getCheckedKeys()
      let halfCheckedKeys = this.$refs.treeRef.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
  }
}
</script>
